package com.easy.component.network.request;

import android.text.TextUtils;

import com.easy.component.network.EasyHttpManager;
import com.easy.component.network.callback.CallBack;
import com.easy.component.network.exception.ApiException;
import com.easy.component.network.utils.NetWorkLogger;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Okhttp3FromTask {
    private String TAG = EasyHttpManager.class.getName();
//    private String url;
//    /**
//     * 回调
//     */
//    private CallBack callBack;
//    /**
//     * 设置参数
//     */
//    public Map<String, Object> parameter;
    /**
     * okhttp
     */
    private OkHttpClient.Builder builder;

    public Okhttp3FromTask() {
        //设置超时时间及缓存
//        int cacheSize = 10 * 1024 * 1024;
        builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
//                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
    }

    /**
     * 上传文件及参数
     */
    public void sendMultipart(String url, Map<String, Object> parameter, final CallBack callBack) {
        OkHttpClient mOkHttpClient = builder.build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Iterator iter = parameter.entrySet().iterator(); iter.hasNext(); ) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            Object value = entry.getValue();
            if (value instanceof File) {
                File file = (File) value;
                mbody.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file));
            } else {
                mbody.addFormDataPart(key, null == value ? "" : value + "");
            }
        }
        RequestBody requestBody = mbody.build();
        Request request = new Request.Builder()
//                .header("User-Agent", "browser_data")
                .url(url)
                .post(requestBody)
                .build();

        mOkHttpClient.newCall(request).enqueue(new okhttp3.Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    Headers headers = response.headers();
                    if (!TextUtils.isEmpty(headers.get("auth"))) {
                        callBack.onLoinError();
                        return;
                    }
                    String body = response.body().string() + "";
                    NetWorkLogger.i(TAG, "---responseBody--->" + body);
                    if (callBack.mType == String.class) {
                        callBack.onSuccess(body);
                    } else {
                        callBack.onSuccess(new Gson().fromJson(body, callBack.mType));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onError(new ApiException(e));
                }
            }
        });
    }

    private String getSuffix(File file) {
        String suffix;
        String fileName = file.getName();
        suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }
}
